package com.bird.thread.base.stopthread;

/**
 * @author sijunqiang
 * @data 2021/6/26 16:06
 * @description: 中断线程的最佳实践-2
 * 在catch子语句中调用Thread.currentThread().interrupt().来恢复设置中断状态,
 * 以便在后续的执行中,依然能够检查到刚才发生了中断 回到刚才RightWayStopThreadWitInProd2
 * 补上中断 让它跳出。
 */
public class RightWayStopThreadWitInProd2 implements Runnable {

    @Override
    public void run() {
        while (true) {
            // 判断是否中断了
            if (Thread.currentThread().isInterrupted()) {
                System.out.println("Interrupt,程序运行结束");
                //处理中断之后的逻辑
                break;
            }
            reInterrupt();
        }
    }

    // run 方法里面调用他人的方法。重新恢复中断信号
    private void reInterrupt() {
        System.out.println("reInterrupt method...");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // 恢复中断信号
           Thread.currentThread().interrupt();
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new RightWayStopThreadWitInProd2());
        thread.start();
        Thread.sleep(1000);
         thread.interrupt();
    }
}
